package com.rc.saas.tenant.service.transfer;

import com.rc.saas.tenant.dto.TransPayWalletInfoDto;
import com.rc.saas.tenant.dto.TransPayWalletResultDto;
import com.rc.saas.tenant.mapper.member.MemberAccountMapper;
import com.rc.saas.tenant.mapper.member.MemberAccountRecordMapper;
import com.rc.saas.tenant.mapper.transfer.MemberRefundApplyMapper;
import com.rc.saas.tenant.mapper.transfer.TransferOrderMapper;
import com.rc.saas.tenant.model.member.MemberAccount;
import com.rc.saas.tenant.model.member.MemberAccountRecord;
import com.rc.saas.tenant.model.transfer.MemberRefundApply;
import com.rc.saas.tenant.model.transfer.MemberRefundApplyExample;
import com.rc.saas.tenant.model.transfer.TransferOrder;
import com.rc.saas.tenant.model.transfer.TransferOrderExample;
import com.rc.saas.tenant.vo.member.MemberRechargeVo;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Created by Sven on 2021/08/11
 */
@Service
public class TransferOrderServiceImpl implements TransferOrderService {
    private static Logger logger = LogManager.getLogger(TransferOrderServiceImpl.class);

    @Autowired
    private TransferOrderMapper transferOrderMapper;

    @Autowired
    private MemberAccountMapper memberAccountMapper;

    @Autowired
    private MemberAccountRecordMapper memberAccountRecordMapper;

    @Autowired
    private MemberRefundApplyMapper memberRefundApplyMapper;

    @Override
    public TransferOrderMapper getMapper() {
        return transferOrderMapper;
    }

    @Override
    public void insertSelectiveReturnId(TransferOrder transferOrder) {
        transferOrderMapper.insertSelectiveReturnId(transferOrder);
    }

    @Override
    public void updateSuccessTransferOrder(Long transferOrderId, TransPayWalletResultDto transPayWalletResult, TransPayWalletInfoDto transPayWalletInfo) {
        TransferOrder transferOrder = transferOrderMapper.selectByPrimaryKey(transferOrderId);

        //到帐状态 0未到帐  1已到帐 默认0
        if (null != transferOrder && !("1".equals(transferOrder.getStatus()))) {
            Date date = new Date();

            //1 修改付款单状态
            TransferOrder updateTransferOrder = transferOrderMapper.selectByPrimaryKey(transferOrderId);
            updateTransferOrder.setTransferOrderId(transferOrderId);
            updateTransferOrder.setTransactionId(transPayWalletResult.getPayment_no());
            updateTransferOrder.setPaymentTime(transPayWalletResult.getPayment_time());
            updateTransferOrder.setStatus("1");
            updateTransferOrder.setLastUpdatedTime(date);
            transferOrderMapper.updateByPrimaryKeySelective(updateTransferOrder);

            //2 修改用户余额member_account
            MemberAccount memberAccount = memberAccountMapper.selectByPrimaryKey(transferOrder.getMemberId());
            if (memberAccount == null) {
                logger.error("找不到会员余额记录:{}", transferOrder.getMemberId());
                throw new RuntimeException("找不到会员余额记录");
            }

            MemberRechargeVo memberRechargeVo = new MemberRechargeVo();
            memberRechargeVo.setTenantCode(transferOrder.getTenantCode());
            memberRechargeVo.setMemberId(transferOrder.getMemberId());
            memberRechargeVo.setAmount(transferOrder.getAmount());
            memberAccountMapper.updateMemberAccountByMemberId(memberRechargeVo);

            //3 新增余额变动记录
            MemberAccountRecord memberAccountRecord = new MemberAccountRecord();
            memberAccountRecord.setTenantCode(transferOrder.getTenantCode());
            memberAccountRecord.setMemberId(transferOrder.getMemberId());
            memberAccountRecord.setLocalTradeNo(transferOrder.getOutTradeNo());

            //支付的账户类型 0个人钱包 1企业钱包 默认0
            memberAccountRecord.setAccountType("0");

            //记录类型(记录类型(0会员在线充值,1支出,2转账收入,3分配余额,4后台订单调整,5平台赠送,6积分兑换 7回收金额 8平台钱包充值 9分销返利 10资源占用费 11平台扣费 12 数据迁移 13共享额度变更 14后台退款))
            memberAccountRecord.setRecordType("14");

            //本次变更金额
            memberAccountRecord.setAmount(transferOrder.getAmount());

            //累计后的account
            memberAccountRecord.setResult(memberRechargeVo.getAccount());

            memberAccountRecord.setRemark("后台退款");
            memberAccountRecord.setCreatedTime(date);
            memberAccountRecord.setLastUpdatedTime(date);
            memberAccountRecordMapper.insertSelective(memberAccountRecord);

            //MemberRefundApplyExample example = new MemberRefundApplyExample();
            //example.createCriteria().andRefundApplyIdEqualTo(updateTransferOrder.getRefundApplyId());
            //List<MemberRefundApply> memberRefundApplies = memberRefundApplyMapper.selectByExample(example);
            //if (CollectionUtils.isEmpty(memberRefundApplies)) {
            //    logger.error("memberRefundApply不存在申请记录");
            //}
            //MemberRefundApply memberRefundApply = memberRefundApplies.get(0);

            MemberRefundApply memberRefundApply = memberRefundApplyMapper.selectByPrimaryKey(updateTransferOrder.getRefundApplyId());
            if (memberRefundApply == null) {
                logger.error("memberRefundApply 不存在申请记录:{}", updateTransferOrder.getRefundApplyId());
            }

            //审核状态 0未审核，1已处理，2驳回 3提现中 4已到账 5提现失败 默认0
            memberRefundApply.setStatus("4");
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            memberRefundApply.setPaymentTime(formatter.format(date));

            memberRefundApplyMapper.updateByPrimaryKeySelective(memberRefundApply);

            logger.info("充值入账成功,tenantCode:{},memberId:{},outTradeNo:{},充值金额,:{},新的余额,:{}",
                    transferOrder.getTenantCode(), transferOrder.getMemberId(), transferOrder.getOutTradeNo(),
                    transferOrder.getAmount(), memberRechargeVo.getAccount());
        }
    }

    @Override
    public void updateFailTransferOrder(Long transferOrderId, String retryTransfersReq, String retryGettransferinfoReq, TransPayWalletResultDto transPayWalletResult) {
        TransferOrder transferOrder = transferOrderMapper.selectByPrimaryKey(transferOrderId);

        //到帐状态 0未到帐  1已到帐 默认0
        if (null != transferOrder && !("1".equals(transferOrder.getStatus()))) {
            //保存错误信息
            TransferOrder updateTransferOrder = new TransferOrder();
            updateTransferOrder.setTransferOrderId(transferOrderId);
            updateTransferOrder.setErrCode(transPayWalletResult.getErr_code());
            updateTransferOrder.setErrCodeDes(transPayWalletResult.getErr_code_des());
            updateTransferOrder.setRetryTransfersReq(retryTransfersReq);
            updateTransferOrder.setRetryGettransferinfoReq(retryGettransferinfoReq);
            updateTransferOrder.setStatus("2");
            transferOrderMapper.updateByPrimaryKeySelective(updateTransferOrder);
        }
    }

    @Override
    public long countFailTransferOrderByMember(Long memberId) {
        TransferOrderExample example = new TransferOrderExample();
        example.createCriteria().andMemberIdEqualTo(memberId).andStatusEqualTo("0");
        return transferOrderMapper.countByExample(example);
    }

    @Override
    public TransferOrder selectTransferOrderByOutTradeNo(String tenantCode, String outTradeNo) {
        TransferOrderExample example = new TransferOrderExample();
        example.createCriteria().andTenantCodeEqualTo(tenantCode).andOutTradeNoEqualTo(outTradeNo);

        List<TransferOrder> list = transferOrderMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(list)) {
            return list.get(0);
        }
        return null;
    }

    @Override
    public TransferOrder selectByRefundApplyId(Long refundApplyId) {
        TransferOrderExample example = new TransferOrderExample();
        example.createCriteria().andRefundApplyIdEqualTo(refundApplyId);
        List<TransferOrder> transferOrders = transferOrderMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(transferOrders)) {
            return null;
        }
        return transferOrders.get(0);
    }
}
